package com.ruan.lkx.service;

import com.alibaba.fastjson.JSONObject;
import com.ruan.lkx.Constants;
import com.ruan.lkx.bean.GetBlockHash;
import com.ruan.lkx.net.HttpUtils;

import java.io.BufferedReader;
import java.net.HttpURLConnection;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: likaixin
 * @emial: 2638784520@qq.com
 * @desc: 该类用于调用比特币的rpc功能,获取最新区块的哈希值
 * @datetime: 2021-12-13 22:48
 */
public class GetBestBlockHash {

    public GetBlockHash getBestBlockHash(){
        //准备用户信息
        String auth=Constants.BITCOIN_RPC_USER+":"+Constants.BITCOIN_RPC_PWD;
        //base64编码
        Base64.Encoder encoder=Base64.getEncoder();
        String authBase64=encoder.encodeToString(auth.getBytes());
        //准备请求头
        Map<String,String> header=new HashMap<>();
        header.put("ContentType","application/json");
        header.put("Authorization","Basic "+authBase64 );
        //准备请求数据
        Map<String,Object> body=new HashMap<>();
        body.put("id",1001);
        body.put("method","getbestblockhash");
        body.put("params",null);
        body.put("json_rpc","2.0");
        byte[] bodyBytes= JSONObject.toJSONBytes(body);

        String result = HttpUtils.post(Constants.BITCOIN_RPC_URL, header, bodyBytes);
        GetBlockHash getBestBlockHash = JSONObject.parseObject(result, GetBlockHash.class);

        return getBestBlockHash;

    }

}
